package com.tsmti.system.service.impl;


import com.tsmti.core.common.constant.Constants;
import com.tsmti.core.common.service.impl.BaseServiceImpl;
import com.tsmti.core.util.ObjectUtils;
import com.tsmti.system.entity.Menu;
import com.tsmti.system.entity.Organization;
import com.tsmti.system.service.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Title：PimsSystem
 * Class：com.ts.sys.service.impl
 * Comapny:
 *
 * @author：zcw
 * @version：2.5 CreateTime：2018/1/17 17:08
 * Modify log:
 * Description：
 */

@Transactional(rollbackFor = Exception.class)
@Service("menuService")
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {

    @Override
    public List<Menu> findTopMenuByUserId(long userId) {
        return findByHql(" from Menu where  parentId is null and  m.id in (SELECT rm.menuId from RoleMenu rm WHERE rm.roleId in (SELECT ur.roleId from UserRole ur WHERE ur.userId=?)) and type="+ Constants.MENU_TYPE_MENU+" ORDER BY sort ASC", userId);
    }
    @Override
    public List<Menu> findMenuByUserId(long userId) {
        return findByHql("  from Menu where  id in (SELECT rm.menuId from RoleMenu rm WHERE rm.roleId in (SELECT ur.roleId from UserRole ur WHERE ur.userId=?)) and type="+ Constants.MENU_TYPE_MENU+" ORDER BY sort ASC", userId);
    }

    @Override
    public List<Menu> findMenuByRoleId(long roleId) {
        return findByHql(" from Menu where  id in (SELECT rm.menuId from RoleMenu rm WHERE rm.roleId=?) and type="+ Constants.MENU_TYPE_MENU, roleId);
    }

    /**
     * 保存、设置parentIds
     * @param entity
     * @return
     */
    @Override
    public Menu save(Menu entity) {
        if (!ObjectUtils.isNullOrEmpty(entity.getParentId())) {
            Menu parent = get(entity.getParentId());
            entity.setParentId(parent.getId());
            entity.setParentIds(parent.makeSelfAsNewParentIds());
        } else {
            entity.setParentId(null);
        }
        return super.save(entity);
    }
}

